package cn.zn.framework.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.common.enums.UserStatus;
import cn.zn.base.exception.BaseException;
import cn.zn.framework.bean.LoginUser;
import cn.zn.menu.service.SysMenuService;
import cn.zn.role.entity.SysRole;
import cn.zn.role.service.SysRoleService;
import cn.zn.user.entity.SysUser;
import cn.zn.user.entity.SysUserJz;
import cn.zn.user.service.SysUserJzService;
import cn.zn.user.service.SysUserService;
import cn.zn.user.vo.SysUserJzPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author zn-admin
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserJzService userJzService;

    private final static String LOGIN = "LOGIN";

    private final static String SSO = "SS0";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取登录名
        String loginName = username;
        String loginFlag = LOGIN;
        if (StrUtil.endWith(username, Constants.SSO_TYPE)) {
            loginName = StrUtil.subBefore(username, Constants.SSO_TYPE, true);
            loginFlag = SSO;
        }

        SysUser user = userService.selectUserByLoginName(loginName);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", loginName);
            throw new UsernameNotFoundException("登录用户：" + loginName + " 不存在");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", loginName);
            throw new BaseException("对不起，您的账号：" + loginName + " 已停用");
        }

        // 获取兼职
        SysUserJzPageVo vo = new SysUserJzPageVo();
        vo.setUserCode(user.getLoginName());
        List<SysUserJz> userJzs = userJzService.selectUserJzList(vo);
        List<String> jzOrgIds = new ArrayList<>();
        List<String> frOrgIds = new ArrayList<>();
        if (CollUtil.isNotEmpty(userJzs)) {
            userJzs.forEach(item -> {
                if ("Z".equals(item.getOrgType())) {
                    jzOrgIds.add(item.getOrgId());
                } else if ("F".equals(item.getOrgType())) {
                    frOrgIds.add(item.getOrgId());
                }
            });
        }
        user.setJzOrgIds(jzOrgIds);
        user.setFrOrgIds(frOrgIds);
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        // 管理员拥有所有权限
        Set<String> perms = menuService.selectMenuPermsByUserId(user.getId(), user.getLoginName());
        List<SysRole> roles = roleService.selectRolesByUserId(user.getId());
        user.setRoles(roles);
        return new LoginUser(user, perms);
    }
}
